package test;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2023-01-10
 * Time: 22:03
 */
class MyThreadPool{
    //组织任务
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    //创建一个工作线程 工作线程的任务就是从上述队列中去数据
    static class Worker extends Thread{
        private BlockingQueue<Runnable> queue = null;

        //构造方法
        public Worker(BlockingQueue<Runnable> queue){
            this.queue = queue;
        }

        public void run(){
            //拿到上面的任务队列
            while (true){
                try {
                    Runnable runnable = queue.take();
                    //获取执行 就执行任务
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //4。创建一个数据结构来组织若干个线程
    private List<Thread> workers = new ArrayList<>();

    public MyThreadPool(int n){
        //构造方法中 创建若干线程
        for (int i = 0; i < n; i++) {
            Worker worker = new Worker(queue);
            worker.start();
            workers.add(worker);
        }
    }

    //创建一个方法将任务添加到线程池
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


//线程池
public class Demo6 {
    public static void main(String[] args) {
        MyThreadPool myThreadPool = new MyThreadPool(10);
        for (int i = 0; i < 100; i++) {
            myThreadPool.submit(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("haha");
                }
            });
        }
    }
}
